<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="prodName">
        <el-input v-model="queryParams.prodName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="上架时间" prop="putawayTime">
        <el-date-picker clearable v-model="queryParams.putawayTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择上架时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="品牌" prop="brand">
        <el-input v-model="queryParams.brand" placeholder="请输入品牌" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:AppProd:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:AppProd:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:AppProd:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:AppProd:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="AppProdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="产品ID" align="center" prop="prodId" /> -->
      <el-table-column label="商品名称" align="center" prop="prodName" />
      <el-table-column label="原价" align="center" prop="oriPrice" />
      <el-table-column label="现价" align="center" prop="price" />
      <el-table-column label="描述/卖点" align="center" prop="brief" />
      <!--      <el-table-column label="详细描述" align="center" prop="content" />-->
      <el-table-column label="商品主图" align="center" prop="pic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.pic" :width="50" :height="50" />
        </template>
      </el-table-column>
      <!--      <el-table-column label="商品图片，以,分割" align="center" prop="imgs" />-->
      <el-table-column label="正常/删除/下架" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 1 ? '正常' : scope.row.status == -1 ? '删除' : '下架' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="categoryId" />
      <el-table-column label="销量" align="center" prop="soldNum" />
      <el-table-column label="总库存" align="center" prop="totalStocks" />
      <el-table-column label="配送方式" align="center" width="200px" prop="deliveryMode">
        <template slot-scope="scope">
          <span>{{ scope.row.deliveryMode.hasShopDelivery ? '店铺送货' : '用户自提' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="运费模板id" align="center" prop="deliveryTemplateId" /> -->
      <el-table-column label="上架时间" align="center" prop="putawayTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.putawayTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="point" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:AppProd:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:AppProd:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :fullscreen="true">
      <el-form :model="dataForm" ref="dataForm" label-width="100px">
        <el-form-item label="产品图片">
          <!-- <image-upload v-model="dataForm.imgs" /> -->
          <el-upload name="multipartFile" ref="uploadComp" :action="upUrlT" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-success="imgSuccess" :on-error="imgError" :on-remove="imgRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="产品名称" prop="prodName" :rules="[
          { required: true, message: '产品名称不能为空' },
          { pattern: /\s\S+|S+\s|\S/, message: '请输入正确的产品名称', trigger: 'blur' }
        ]">
          <el-col :span="8">
            <el-input v-model="dataForm.prodName" placeholder="产品名称" maxlength="50"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-col :span="8">
            <el-input v-model="dataForm.brand" placeholder="品牌" maxlength="50"></el-input>
          </el-col>
        </el-form-item>


        <el-form-item label="厂家" prop="shop">
          <el-select v-model="dataForm.shopId" placeholder="请选择厂家:" clearable>
            <el-option v-for="dict in shops" :key="dict.shopId" :label="dict.shopName" :value="dict.shopId" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="dataForm.categoryId" placeholder="请选择商品分类:" clearable>
            <el-option v-for="dict in categorys" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品类型" prop="goodTypes">
          <el-select v-model="dataForm.type" placeholder="请选择商品分类:" clearable>
            <el-option v-for="dict in goodTypes" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品参数" prop="addParam">
          <el-button type="primary" plain @click="addItemAction">添加参数</el-button>
        </el-form-item>


        <el-form-item prop="paramList">
          <div v-for="(inputComp, index) in dataForm.prodParamsList" :key="index">

            <el-col :span="8">
              <el-form-item label="参数名称">
                <el-input type="text" v-model="inputComp.paramName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="参数值">
                <el-input type="text" v-model="inputComp.paramValue" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label=" ">
                <el-button @click="deleteParamItem(index)" type="danger" plain>删除</el-button>
              </el-form-item>
            </el-col>
          </div>
        </el-form-item>

        <el-form-item label="标签（用英文逗号分割）" prop="label">
          <el-col :span="8">
            <el-input v-model="dataForm.label" placeholder="标签" maxlength="50"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="产品卖点" prop="brief" :rules="[
          { required: false, pattern: /\s\S+|S+\s|\S/, message: '请输入正确的产品卖点', trigger: 'blur' }
        ]">
          <el-col :span="8">
            <el-input v-model="dataForm.brief" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="产品卖点"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="配送方式">
          <el-checkbox v-model="dataForm.deliveryMode.hasShopDelivery">商家配送</el-checkbox>
          <el-checkbox v-model="dataForm.deliveryMode.hasUserPickUp">用户自提</el-checkbox>
        </el-form-item>
        <prod-transport v-show="dataForm.deliveryMode.hasShopDelivery"
          v-model="dataForm.deliveryTemplateId"></prod-transport>
        <sku-tag ref="skuTag" :skuList="dataForm.skuList" @change="skuTagChangeSkuHandler" v-if="showSKU"></sku-tag>
        <sku-table ref="skuTable" v-model="dataForm.skuList" :prodName.sync="dataForm.prodName"
          v-if="showSKU"></sku-table>

        <el-form-item label="产品详情" prop="content">
          <!--        <tiny-mce v-model="dataForm.content"-->
          <!--                  ref="content"-->
          <!--                  style="width:1000px"></tiny-mce>-->
          <editor v-model="dataForm.content" :min-height="192" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppProd, getAppProd, delAppProd, addAppProd, updateAppProd } from "@/api/system/AppProd";
import ProdTransport from './prod-transport'
import SkuTag from './sku-tag'
import SkuTable from './sku-table'
import { listShopdetail } from "@/api/system/shopdetail"
// import TinyMce from '@/components/tiny-mce'
import { Debounce } from '@/utils/debounce'

export default {
  name: "AppProd",
  components: {
    ProdTransport,
    SkuTag,
    SkuTable
  },
  data() {
    return {
      categorys: [{ id: 0, name: "免费" }, { id: 1, name: "音乐会" }, { id: 2, name: "精选" }],
      goodTypes: [{ id: 0, name: "积分兑换福利" }, { id: 1, name: "钢琴好物" }],
      shops: [],

      upUrlT: process.env.VUE_APP_BASE_API + '/v1/app/public/upload',
      showSKU: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      AppProdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // distinguish:1,
        prodName: null,
        shopId: null,
        oriPrice: null,
        price: null,
        brief: null,
        content: null,
        pic: null,
        imgs: null,
        status: null,
        categoryId: null,
        soldNum: null,
        totalStocks: null,
        deliveryMode: null,
        deliveryTemplateId: null,
        putawayTime: null,
        version: null,
        point: null,
        brand: null
      },
      // 表单参数
      // 规格列表
      dataForm: {
        prodName: '',
        brief: '',
        pic: '',
        imgs: '',
        categoryId: 0,
        prodId: 0,
        skuList: [],
        tagList: [],
        content: '',
        status: 1,
        prodParamsList: [],
        deliveryMode: {
          hasShopDelivery: false,
          hasUserPickUp: false
        },
        deliveryTemplateId: null
      },
      // 表单校验
      rules: {
        prodName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getShopsInfo();
  },
  computed: {
    defalutSku() {
      return this.$store.state.prod.defalutSku
    }
  },
  // activated () {
  //     this.dataForm.prodId = this.$route.query.prodId
  //     this.getDataList()
  // },
  methods: {
    getDataList() {
      if (this.dataForm.prodId) {
        getAppProd(this.dataForm.prodId).then(res => {
          this.dataForm = res.data
          this.dataForm.deliveryMode = JSON.parse(res.data.deliveryMode)
          this.$refs.skuTag.init(res.data.skuList)
          this.$refs.skuTable.init()

        })
      } else {
        this.reset()
        this.$refs.skuTag.init()
        this.dataForm.pic = ''
        this.dataForm.imgs = ''
      }

    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listAppProd(this.queryParams).then(response => {
        response.rows.forEach(element => {
          if(element.distinguish == 1 || element.distinguish == null){
          this.AppProdList.push(element);
          }
        });
        this.total = this.AppProdList.length;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$parent.showSKU = false
      this.reset();
      this.$refs.uploadComp.clearFiles()
    },
    // 表单重置
    reset() {
      this.dataForm = {
        prodName: '',
        brief: '',
        pic: '',
        imgs: '',
        categoryId: 0,
        prodId: 0,
        skuList: [],
        tagList: [],
        content: '',
        status: 1,
        prodParamsList: [],

        deliveryMode: {
          hasShopDelivery: false,
          hasUserPickUp: false
        },
        deliveryTemplateId: null
      };
      this.resetForm("dataForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.prodId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(id) {
      this.reset();
      this.showSKU = true
      this.open = true;
      this.title = "添加商品";
      this.$nextTick(() => {
        this.$refs.skuTag.init()
        this.$refs.skuTable.init()
      })


      this.dataForm.pic = ''
      this.dataForm.imgs = ''
      //   this.$router.push({
      //       path: '/prodInfo',
      //       query: { prodId: id }
      //   })
    },



    imgSuccess(response, file, fileList) {

      if (response.code == 200) {
        this.dataForm.imgs = response.data.url
      }
      console.log(this.dataForm.imgs)

    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.showSKU = true
      const prodId = row.prodId || this.ids
      getAppProd(prodId).then(response => {
        this.dataForm = response.data;
        this.dataForm.deliveryMode = JSON.parse(response.data.deliveryMode)
        this.$nextTick(() => {
          this.$refs.skuTag.init(response.data.skuList)
          this.$refs.skuTable.init()
        })

        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let that = this
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return
        }
        if (!that.dataForm.imgs) {
          this.errorMsg('请选择图片上传')
          return
        }
        if (!that.dataForm.deliveryMode) {
          this.errorMsg('请选择配送方式')
          return
        }
        if (that.dataForm.deliveryMode.hasShopDelivery && !that.dataForm.deliveryTemplateId) {
          this.errorMsg('请选择运费模板')
          return
        }
        let param = Object.assign({}, that.dataForm)
        // 设置价格和库存
        this.paramSetPriceAndStocks(param)

        param.deliveryMode = undefined
        param.deliveryModeVo = that.dataForm.deliveryMode
        // 商品主图
        param.pic = this.dataForm.imgs.split(',')[0]
        param.distinguish = 1;
        if (param.prodId) {
          updateAppProd(param).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          addAppProd(param).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }

      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prodIds = row.prodId || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + prodIds + '"的数据项？').then(function () {
        return delAppProd(prodIds);
      }).then(() => {
        
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/AppProd/export', {
        ...this.queryParams
      }, `AppProd_${new Date().getTime()}.xlsx`)
    },
    paramSetPriceAndStocks(param) {
      // 获取规格属性信息
      // param.skuList = this.$refs.prodSpec.getTableSpecData()
      // 商品库存
      param.totalStocks = 0
      // 商品价格
      param.price = 0
      // 商品原价
      param.oriPrice = 0
      // 商品实际库存
      for (let i = 0; i < param.skuList.length; i++) {
        const element = param.skuList[i]
        if (element.status !== 1) {
          continue
        }
        if (param.price === 0) {
          param.price = element.price ? Number.parseFloat(element.price) : 0
        }
        // 商品价格为最低价的那件商品的价格
        param.price = Math.min(param.price, element.price)
        if (param.price === element.price) {
          param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
        }
        param.totalStocks += element.stocks ? Number.parseInt(element.stocks) : 0
      }
      // 如果sku没有商品名称，则使用商品的商品名称
      if (param.skuList.length === 1) {
        param.skuList[0].prodName = this.dataForm.prodName
      }
    },
    skuTagChangeSkuHandler(skuList) {
      const prodName = this.dataForm.prodName
      skuList.forEach(sku => {
        if (sku.properties) {
          sku.skuName = ''
          let properties = sku.properties.split(';')
          for (const propertiesKey in properties) {
            sku.skuName += properties[propertiesKey].split(':')[1] + ' '
          }
          sku.prodName = prodName + ' ' + sku.skuName
        }
      })
      this.dataForm.skuList = skuList
    },

    getShopsInfo() {
      listShopdetail().then(res => {
        this.shops = res.rows
      })
    },
    deleteParamItem(idx) {
      this.dataForm.prodParamsList.splice(idx, 1)
      //   var tmp = []
      //   for(let i = 0;i<this.dataForm.paramList.length;i++){
      //       if(i != idx){
      //           tmp.push(this.dataForm.paramList[i])
      //       }
      //   }
      //   debugger
      // this.dataForm.paramList = tmp
    },
    addItemAction() {
      let itm = { paramName: "", paramValue: "" }
      this.dataForm.prodParamsList.push(itm)
    }
  }
};
</script>
